<template>
  <div class="tiny-editor">
    <a-skeleton :loading="loadingEditor" avatar :paragraph="{ rows: 2 }" active> </a-skeleton>
    <Editor v-model="innerContent" :api-key="TinyMCEKey" :init="editorInit" @init="onEditorInit" @blur="handleBlurFn" />
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, ref, watch, nextTick } from "vue";
import Editor from "@tinymce/tinymce-vue";
import { getTinyMCELangInfo } from "/@/utils/tinymce";
import env from "/@/base/env";
import { Api, uploadReq } from "/@/api/common";
import { TinyMCEKey } from "/@/base/data";

const props = defineProps<{
  value: string;
  height?: number;
}>();

const emits = defineEmits(["change"]);

const innerContent = ref("");

const editorInit = {
  height: props.height || 1200,
  menubar: false,
  plugins: ["image"],
  // plugins: "link",
  contextmenu: "bold copy link paste",
  toolbar1:
    "undo redo | link bold italic underline strikethrough image | alignleft aligncenter alignright alignjustify | forecolor backcolor removeformat",
  images_upload_handler: async function (blobInfo) {
    const file = blobInfo.blob(); //转化为易于理解的file对象
    let formData = new FormData();
    formData.append("file", file);
    let url = env.baseUrl + "/" + Api.upload;
    let re = await uploadReq(url, formData);
    console.log("=====>upload req", re);
    if (re && re.data) {
      return re.data.url;
      // success(re.data.url);
    } else {
      console.log("upload fail", re);
      // failure("上传失败，请稍候再试");
      throw "上传失败，请稍候再试";
    }
  },
  content_style: `body{margin: 0}
  img{width: 100% !important;height: auto !important}
  p{margin: 0}
  p:has(img){font-size:0}`,
  object_resizing: false,
  file_picker_types: "image",
  file_picker_callback(cb, value, meta) {
    console.log(cb, "value:", value, "meta", meta);
    cb(value, { width: "100%", height: "auto" });
  },
};
// console.info("innerContent==>", innerContent.value);
const langInfo = getTinyMCELangInfo();
if (langInfo) {
  Object.assign(editorInit, langInfo);
}
const loadingEditor = ref(true);
watch(
  () => props.value,
  (v) => {
    nextTick(() => {
      innerContent.value = v || "";
    });
  }
);
watch(loadingEditor, (v) => {
  if (v) {
    nextTick(() => {
      innerContent.value = props.value || "";
    });
  }
});
watch(innerContent, (v) => {
  emits("change", v);
});
function onEditorInit() {
  loadingEditor.value = false;
  nextTick(() => {
    innerContent.value = props.value || "";
  });
}
function handleBlurFn(v) {
  emits("change", innerContent.value);
}
</script>
<style lang="less">
.tiny-editor {
  textarea {
    display: none;
  }
}

.tox .tox-edit-area::before {
  border: 0 !important;
}
</style>
